package com.buddies.lottery.base;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.buddies.lottery.R;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.exception.ApiException;
import com.buddies.lottery.exception.DefineException;
import com.buddies.lottery.ui.login.LoginActivity;
import com.buddies.lottery.utils.AlarmUtils;
import com.buddies.lottery.widget.ProgressDialog;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.bugly.crashreport.BuglyLog;
import com.tencent.bugly.crashreport.CrashReport;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import retrofit2.HttpException;

/**
 * Description: Activity基类
 * Date: 2018/2/11
 * Author: xuliang
 */
public abstract class BaseActivity<P extends IPresenter> extends RxAppCompatActivity implements IView {

    protected final String TAG = getClass().getSimpleName();

    protected Handler mHandler = new Handler();
    protected KProgressHUD mProgressDialog;
    protected P mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        initView();
        initData();
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    protected void setUp() {
        setOnUpClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    protected void setOnUpClickListener(View.OnClickListener listener) {
        View ivUp = findViewById(R.id.iv_up);
        if (ivUp != null) {
            ivUp.setVisibility(View.VISIBLE);
            ivUp.setOnClickListener(listener);
        }
    }

    protected void setTitle(String title) {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        if (tvTitle != null) {
            tvTitle.setText(title);
        }
    }

    protected void setOnTitleClickListener(View.OnClickListener listener) {
        View title = findViewById(R.id.tv_title);
        if (title != null) {
            title.setOnClickListener(listener);
        }
    }

    public final void replaceFragment(Fragment fragment, @IdRes int containerId, boolean addToBackStack) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction()
                .replace(containerId, fragment);
        if (addToBackStack) transaction.addToBackStack(null);
        transaction.commitAllowingStateLoss();
    }

    public final void replaceFragment(Fragment fragment, @IdRes int containerId) {
        replaceFragment(fragment, containerId, false);
    }

    protected void postDelayed(Runnable runnable) {
        postDelayed(runnable, 0);
    }

    protected void postDelayed(Runnable runnable, long delay) {
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
            if (!isFinishing()) {
                mHandler.postDelayed(runnable, delay);
            }
        }
    }

    protected void removeDelayed(Runnable runnable) {
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
    }

    public void showToast(int msg) {
        ToastUtils.showShort(msg);
    }

    public void showToast(String msg) {
        ToastUtils.showShort(msg);
    }

    public void showProgressDialog(int resStringId) {
        showProgressDialog(getString(resStringId));
    }

    public void showProgressDialog(String msg) {
        showProgressDialog(msg, true);
    }

    public void showProgressDialog(final String msg, final boolean cancel) {
        showProgressDialog(msg, cancel, null);
    }

    public void showProgressDialog(final String msg, final boolean cancel, DialogInterface.OnCancelListener onCancelListener) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }

        try {
            if (mProgressDialog == null) {
                mProgressDialog = ProgressDialog.show(getActivity(), msg, cancel);
            }
            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
                mProgressDialog.setLabel(msg);
                mProgressDialog.setCancellable(cancel);
                if (onCancelListener != null) {
                    mProgressDialog.setCancellable(onCancelListener);
                }
            } else {
                mProgressDialog.setLabel(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hideProgressDialog() {
        hideProgressDialog(mProgressDialog);
    }

    public void hideProgressDialog(KProgressHUD dialog) {
        ProgressDialog.hide(dialog);
    }

    public FragmentActivity getActivity() {
        return this;
    }

    public Handler getHandler() {
        return mHandler;
    }

    @Override
    public void onError(Throwable e) {
        BuglyLog.e("NetRequest", e.getMessage());

        hideProgressDialog();

        if (e instanceof TimeoutException) {
            ToastUtils.showShort(getString(R.string.connect_timeout));
        } else if (e instanceof HttpException) {
            HttpException error = (HttpException) e;
            int code = error.code();
            if (code == 404) { // 接口未找到
                ToastUtils.showShort(getString(R.string.no_api_error));
            } else if (code >= 500) {
                ToastUtils.showShort(getString(R.string.server_error));
                CrashReport.postCatchedException(e);
                AlarmUtils.getInstance().send("@警告@服务器挂了", "");
            } else {
                String message = "(" + code + ")" + error.message();
                ToastUtils.showShort(message);
            }
        } else if (e instanceof IOException) {
            ToastUtils.showShort(getString(R.string.server_error));
            CrashReport.postCatchedException(e);
        } else if (e instanceof ApiException) {
            // ApiException处理
            ApiException error = (ApiException) e;
            if (error.getCode() == -401) {// 重新登录
                ConfigManager.getInstance().logout();
                LoginActivity.launch(this);
                finish();
            }
            ToastUtils.showShort(error.getMessage());
        } else if (e instanceof DefineException) {
            DefineException exception = (DefineException) e;
            ToastUtils.showShort(exception.getMessage());
        } else {
            ToastUtils.showShort(R.string.unknown_error);
            CrashReport.postCatchedException(e);
        }
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

}
